package com.wjk.kylin.core.common.oss.local;

import cn.hutool.core.util.IdUtil;
import com.wjk.kylin.config.properties.SysProperties;
import com.wjk.kylin.core.common.oss.AbstractOSSServer;
import com.wjk.kylin.core.common.oss.OSSFileModel;
import com.wjk.kylin.core.exception.BusinessException;
import com.wjk.kylin.core.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;


@Slf4j
@Component
public class LocalFileServer extends AbstractOSSServer<OSSFileModel> {
    @Autowired
    private SysProperties sysProperties;

    private final static String FILE_PATH = "C:/Users/admin/Desktop/2021/";
//    private final static String FILE_PATH = "/opt/upload/";

//    @Value("${sys.setting.accessUrl}")
//    private String accessUri;

    @Override
    public String upload(OSSFileModel model) {
        String path = FILE_PATH + DateUtils.formatDate("yyyy/MM/dd") + File.separator;
        tryCreateDir(path);
        File myFile = new File(path + IdUtil.simpleUUID() +"."+model.getExtName());
        try{
            model.getFile().transferTo(myFile);
        } catch (Exception e){
            log.error("上传文件失败,path:{}",myFile.getPath(),e);
            throw new BusinessException("上传文件失败，请检查配置信息");
        }

        return sysProperties.getAccessUrl() + myFile.getName();
    }

    @Override
    protected void delete(String filePath) {

    }

    @Override
    protected File download(String filePath) {
        return null;
    }


    /**
     * 检查目录是否存在，并创建目录
     */
    private void tryCreateDir(String path) {
        File dir = new File(path);
        if(!dir.exists()) {
            if(dir.mkdirs()) {
                log.info("目录{}不存在，创建目录成功", path);
            }else {
                log.warn("创建目录{}失败", path);
            }
        }
    }
}
